import { toast } from '@/utils/extendApi'
import { reqLogin, reqUserInfo } from '@/api/user'
import { setStorage } from '@/utils/storage'
import { ComponentWithStore } from 'mobx-miniprogram-bindings'
import { userStore } from '@/stores/userStore'

// 防抖
import { debounce } from 'miniprogram-licia'
ComponentWithStore({
  storeBindings: {
    store: userStore,
    fields: ['token', 'userInfo'],
    actions: ['setToken', 'setUserInfo']
  },
  methods: {
    login: debounce(function () {
      // 使用wx.login来获取临时登录凭证code
      wx.login({
        success: async ({ code }) => {
          // console.log({ code })
          if (code) {
            const res = await reqLogin(code)
            // console.log(res)
            setStorage('token', res.data.token)
            this.setToken(res.data.token)
            this.getUserInfo()
            wx.navigateBack()
          } else {
            toast({
              title: '授权失败 请重新授权'
            })
          }
        }
      })
    }, 500),
    async getUserInfo() {
      const res = await reqUserInfo()
      // console.log(res)
      setStorage('userInfo', res.data)
      this.setUserInfo(res.data)
    }
  }
})
